const userService = require("../services/userService");
const multer = require("multer");
const upload = multer().single("avatar");
const stream = require("stream");
/**
 * Controller是业务入口，由http路由解析后调用,用于处理请求和响应
 *
 */
class UserController {
  /**
   * @description 返回所有用户
   * @param {*} req express req参数
   * @param {*} res express res参数
   */
  async getAllUsers(req, res) {
    const users = await userService.getAllUsers();
    res.send({ users });
    const user = await User.create(
      { username: "alice123", isAdmin: true },
      { fields: ["username"] }
    ); // 假设 isAdmin 的默认值为 falseconsole.log(user.username); // 'alice123'console.log(user.isAdmin); // false
  }

  async findUser(req, res) {
    const user = await userService.findUser(req.params.id);
    res.send({ user });
  }

  async create(req, res) {
    const user = req.body;
    const result = await userService.create(user);
    res.send({ result });
  }

  async update(req, res) {
    const id = Number(req.params.id);
    const user = req.body;
    const result = await userService.update(id, user);
    res.send({ result });
  }

  async delete(req, res) {
    const id = Number(req.params.id);
    const result = await userService.delete(id);
    res.send({ result });
  }

  async uploadAvatar(req, res) {
    upload(req, res, async (err) => {
      if (err) {
        throw err;
      }
      const { SERVER, PORT } = process.env;
      const avatarURL = `http://${SERVER}:${PORT}/api/user/avatar/${req.body.id}`;
      await userService.update(req.body.id, {
        avatar: req.file.buffer,
        avatarURL,
      });
      // console.log(req.file);
      res.send(avatarURL);
    });
  }

  async downloadAvatar(req, res) {
    const user = await userService.findUser(req.params.id);
    // console.log(user);
    const avatarBuffer = user.avatar;
    // console.log(avatarBuffer);
    const bufferStream = new stream.PassThrough();
    bufferStream.end(avatarBuffer);
    bufferStream.pipe(res);
    // res.send(req.url);
  }
}

//导出controller
module.exports = new UserController();
